// @author: caoshi
// @date: 2021-05-10 19:46
package main

import (
	"demo02_html_template/src/pojo"
	"html/template"
	"net/http"
	"time"
)

/**
请求处理函数
*/
func welcome(w http.ResponseWriter, r *http.Request) {
	// 解析html模板
	temp, _ := template.ParseFiles("view/index.html")
	// 执行, 可向模板中传值
	temp.Execute(w, "hello")
}

/**
向模板中传递数据
*/
func welcome2(w http.ResponseWriter, r *http.Request) {
	temp, _ := template.ParseFiles("view/index2.html")

	// 传递简单字符串
	//temp.Execute(w, "张三")

	// 传递结构体对象
	//user := pojo.User{"李四", 12, "武汉市"}
	//temp.Execute(w, user)

	// 传递map集合数据
	data := make(map[string]interface{})
	data["user"] = pojo.User{"王五", 18, "北京朝阳"}
	data["price"] = 998
	temp.Execute(w, data)
}




/**
在模板中调用函数
*/
func doFunc(w http.ResponseWriter, r *http.Request) {
	temp, _ := template.ParseFiles("view/index3.html")
	t1 := time.Date(2021, 5, 10, 21, 21, 23, 0, time.Local)
	// fmt.Println(t1)
	//	fmt.Println(t1.Year())

	// 格式化时间
	temp.Execute(w, t1)
}

func doFunc2(w http.ResponseWriter, r *http.Request) {
	fMap := template.FuncMap{"mt": MyTrandfer}
	// 绑定函数map
	funcs := template.New("index4.html").Funcs(fMap)
	temp,_ := funcs.ParseFiles("view/index4.html")

	t1 := time.Date(2021, 5, 10, 21, 21, 23, 0, time.Local)
	// t1是传递到模板中的参数
	temp.Execute(w, t1)
}

// 自定义函数
func MyTrandfer(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

/**
	测试模板嵌套
 */
func testTemp(w http.ResponseWriter, r *http.Request)  {
	temp, _ := template.ParseFiles("view/index5.html", "view/temp/head.html", "view/temp/foot.html")
	temp.ExecuteTemplate(w, "layout", nil)
}


func main() {
	server := http.Server{Addr: "localhost:8090"}
	// 解析静态资源文件 js, css等
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", welcome)
	http.HandleFunc("/index2", welcome2)
	http.HandleFunc("/doFunc", doFunc)
	http.HandleFunc("/doFunc2", doFunc2)
	http.HandleFunc("/testTemp", testTemp)
	server.ListenAndServe()
}
